package com.android.lovely.api.service

import android.net.Uri
import android.provider.OpenableColumns
import com.android.lovely.api.manager.HttpManager
import com.android.lovely.data.AppConfig
import com.android.lovely.data.LovelyAdId
import com.android.lovely.data.PayData
import com.kotlin.extensions.appContext
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import java.io.InputStream

val systemService = HttpManager.createApi<SystemService>()

interface SystemService {

    @POST("system/conf")
    suspend fun getSystemConfig(): AppConfig

    @POST("system/tab_info")
    suspend fun getTabInfo(): Map<String, Int>

    @POST("sys/translate_text")
    suspend fun translate(@Body params: Map<String, String>): Map<String, String>

    @Multipart
    @POST("system/upload")
    suspend fun upload(@Part image: MultipartBody.Part): Response<ResponseBody>

    @POST("common/ad_config")
    suspend fun getAdmobId(): LovelyAdId

    @POST("system/event_report")
    suspend fun reportEvent(@Body params: Map<String, @JvmSuppressWildcards Any>): Any

    @POST("common/pro_list")
    suspend fun getPayList(@Body params: Map<String, String> = mapOf()): PayData

    @POST("common/verify_order")
    suspend fun orderSignVerify(@Body params: Map<String, @JvmSuppressWildcards Any>): Any

    @POST("u/message_unread_num")
    suspend fun getUnreadMsg(@Body params: Map<String, String> = mapOf()): Map<String, Int>
}

suspend fun Uri.upload(): String {
    return runCatching {
        val body = createRequestBodyFromUri(uri = this@upload)?.let {
            MultipartBody.Part.createFormData(
                "image", fileName(), it
            )
        } ?: return ""
        val response = systemService.upload(body)
        val json = response.body()?.string()
        if (response.isSuccessful && json != null) {
            JSONObject(json).getJSONObject("data").getString("url")
        } else {
            ""
        }
    }.getOrDefault("")
}


fun createRequestBodyFromUri(uri: Uri): RequestBody? {
    val contentResolver = appContext.contentResolver
    val inputStream: InputStream? = contentResolver.openInputStream(uri)
    val contentType: MediaType? = "image/*".toMediaTypeOrNull()
    return inputStream?.readBytes()?.toRequestBody(contentType)
}

fun Uri.fileName(): String? {
    var fileName: String? = null

    // 如果是 "content://" 类型的 URI
    if (scheme == "content") {
        val cursor = appContext.contentResolver.query(this, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1) {
                    fileName = it.getString(nameIndex)
                }
            }
        }
    }

    // 如果是 "file://" 类型的 URI
    if (fileName == null && scheme == "file") {
        fileName = lastPathSegment // 获取路径中的最后一部分作为文件名
    }

    return fileName
}